package com.platform.qujia.constantEnum;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author zph
 * @Desc: 服务上下文Holder
 * @since 2022-07-11
 */
public class ServiceContextHolder {
    private static Logger logger = LoggerFactory.getLogger(ServiceContextHolder.class);

    private static final ThreadLocal<ServiceContext> LOCAL = new InheritableThreadLocal<ServiceContext>() {
        @Override
        protected ServiceContext initialValue() {
            return new ServiceContext();
        }
    };

    public static ServiceContext getContext() {
        if (LOCAL.get() == null) {
            logger.error("service context not exist");
            throw new RuntimeException("service context is null");
        }
        return LOCAL.get();
    }

    public static void set(ServiceContext sc) {
        if (LOCAL.get() != null) {
            LOCAL.remove();
        }
        LOCAL.set(sc);
    }

    public static void cleanUp() {
        try {
            if (LOCAL.get() != null) {
                LOCAL.remove();
            }
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
    }
}
